package cn.wolfcode.rbac.shiro;

import cn.wolfcode.rbac.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/*
Ajax提交的。由于Ajax是异步传输，做一个类，帮我们处理以前的JsonResult
 */
@Component("crmFormAuthenticationFilter")
public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JsonResult json = new JsonResult();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSON.toJSONString(json));
        return false;//不放行
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();
        String msg = "登录异常，请联系管理员";
        if (e instanceof UnknownAccountException) {
            msg = "账号不存在";
        } else {
            msg = "密码错误";
        }
        JsonResult json = new JsonResult(msg, false);
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(json));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }


}
